//
//  ZDBLoginMainViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/22.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBLoginMainViewController.h"
#import "DJLoginEnterTextItemCell.h"
#import "TPKeyboardAvoidingTableView.h"
#import "DJLoginFooterActionView.h"
#import "ZDBRegisterViewController.h"
#import "ZDBForgetViewController.h"
#import "ZDBKeychainTool.h"
#import "YZAuthID.h"
@interface ZDBLoginMainViewController ()
<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)TPKeyboardAvoidingTableView * ks_TableView2;
@property(nonatomic,strong) NSMutableArray * modelsArry2;
@property(nonatomic,strong) DJLoginFooterActionView * footerView;
@end

@implementation ZDBLoginMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self creat_Nav];
    [self creatUI];
    NSLog(@"%@",[ZDBKeychainTool getDeviceIDInKeychain]);
}


-(void)creat_Nav{
    
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
     backButton.frame = CGRectMake(0, -10, 50, 40);
     [backButton setImage:[UIImage imageNamed:@"goBack"] forState:UIControlStateNormal];
     [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
     backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    
    
    UIButton * reBtn = [UIButton buttonWithType:UIButtonTypeCustom];
     reBtn.frame = CGRectMake(0, -10, 50, 40);
//     [reBtn setImage:[UIImage imageNamed:@"goBack"] forState:UIControlStateNormal];
    [reBtn setTitle:@"注册" forState:0];
    [reBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [reBtn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:0];
     [reBtn addTarget:self action:@selector(reBtnClik) forControlEvents:UIControlEventTouchUpInside];
     reBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:reBtn];
    
    
}

-(void)creatUI{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.ks_TableView2];
   [_ks_TableView2 registerNib:[UINib nibWithNibName:@"DJLoginEnterTextItemCell" bundle:nil]  forCellReuseIdentifier:@"DJLoginEnterTextItemCell"];
    
    UIView * headerV = [BBControl createViewWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    headerV.backgroundColor = [UIColor clearColor];
    
    UIImageView * heaserImage = [BBControl createImageViewFrame:CGRectMake(50, 0, kScreenWidth-100, 200) imageName:@"logo-big" ];
    heaserImage.contentMode = UIViewContentModeCenter;
    [headerV addSubview:heaserImage];
    _ks_TableView2.tableHeaderView = headerV;
    
    self.footerView = [[NSBundle mainBundle]loadNibNamed:@"DJLoginFooterActionView" owner:self options:nil].lastObject;
    self.footerView .frame =CGRectMake(0, 0, kScreenWidth, 250);
     _ks_TableView2.tableFooterView = self.footerView;
    
    WEAKSELF
    [self.footerView.fogetBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        ZDBForgetViewController * forVC = [ZDBForgetViewController new];
        forVC.title = @"忘记密码";
        [strongSelf.navigationController pushViewController:forVC animated:YES];
    }];
    
    [self.footerView.loginBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf login_Request];
    }];
    
   // self.footerView.thdLoginBtn.hidden = NO;
    
    
    [self.footerView.wechatBtn add_BtnClickHandler:^(NSInteger tag) {
       STRONGSELFFor(weakSelf);
       
        
    }];
    
}

-(void)login_Request{
//
//    [[SmileHttpTool sharedInstance] request256TextBlock:^(NSInteger code, NSString *message) {
//
//    }];
     [self.view endEditing:YES];
    DJLoginEnterTextItemCell * phoneCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    DJLoginEnterTextItemCell * pswCell = [self.ks_TableView2 cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];

    if (kStringIsEmpty(phoneCell.textTF.text)) {
        [JMNotifyView showNotify:@"请输入正确的手机号" isSuccessful:NO];
        return;
    }
    if ([self  isMobileNumChack:phoneCell.textTF.text]==NO) {
        [JMNotifyView showNotify:@"请输入正确格式的手机号~" isSuccessful:NO];
         return;

    }
    if (kStringIsEmpty(pswCell.textTF.text)) {
             [JMNotifyView showNotify:@"请输入密码" isSuccessful:NO];
             return;
    }

    [self userLoginRequestWith:phoneCell.textTF.text password:pswCell.textTF.text];

}
#pragma mark - 登陆
-(void)userLoginRequestWith:(NSString *)username  password:(NSString *)password{
    
    [self showLoadingAnimation];
    NSString  * loginurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"user_Login"];
       NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
       [diccc setValue:username forKey:@"userName"];
        [diccc setValue:password forKey:@"passWord"];
        [diccc setValue:[NSString stringWithFormat:@"IOS-%@",[ZDBKeychainTool getDeviceIDInKeychain]] forKey:@"mac"];
    //[ZDBKeychainTool getDeviceIDInKeychain]
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :loginurl parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)
           
           if (statusCode==0) {
              [JMNotifyView showNotify:@"登录成功" isSuccessful:YES];
               NSDictionary * dataDicc = [NSDictionary dictionaryWithDictionary:responseObject];
               NSString *  token = [dataDicc jsonString:@"token"];
              [[DJLoginHelper sharedInstance]save_Token:token];
              [[DJLoginHelper sharedInstance]save_UserInfo:[dataDicc jsonDict:@"userinfo"]];
              [kUserDefaults setValue:[dataDicc jsonDict:@"userinfo"] forKey:@"user_loginInfo"];
              [[NSNotificationCenter defaultCenter] postNotificationName:LoginSusessNotificationse object:nil];
              [strongSelf dismissViewControllerAnimated:YES completion:nil];
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }
             
            [strongSelf stopLoadingAnimation];
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
            [self stopLoadingAnimation];
       }];
    
}


#pragma  mark -----tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJLoginEnterTextItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DJLoginEnterTextItemCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self stupCell:cell atIndex:indexPath];
    return cell;
    
}

-(void)stupCell:(DJLoginEnterTextItemCell *)cell  atIndex:(NSIndexPath *)indexPath{
    cell.textTF.tag = indexPath.row;
    [cell.textTF addTarget:self action:@selector(changedTextField:) forControlEvents:UIControlEventEditingChanged];
      
    switch (indexPath.row) {
        case 0:
        {
            cell.textTF.keyboardType = UIKeyboardTypePhonePad;
           // cell.textTF.text = @"musatest3";
            cell.textTF.placeholder = @"请输入手机号";
            cell.iconImage.image = [UIImage imageNamed:@"login_user-1"];
           // [RestrictionInput restrictionInputTextField:cell.textTF maxNumber:10 showView:self.view showErrorMessage:@"用户名长度必须在6~10个字符"];
              cell.textTF.secureTextEntry = NO;
            NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#adadad"]}];
            cell.textTF .attributedPlaceholder = placeholderString;
            NSDictionary * user_loginInfo = [kUserDefaults valueForKey:@"user_loginInfo"];
                         if (!kDictIsEmpty(user_loginInfo)) {
                                     cell.textTF.text = [user_loginInfo jsonString:@"userName"];
                         }
       //     cell.textTF.text = @"13175110051";
        }
            break;
        case 1:
        {
            cell.textTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            NSDictionary * user_loginInfo = [kUserDefaults objectForKey:@"user_loginInfo"];
            if (!kDictIsEmpty(user_loginInfo)) {
                         cell.textTF.text = [user_loginInfo jsonString:@"password"];
                     }
             cell.textTF.placeholder = @"请输入密码（6-12位数字字母组合）";
             cell.textTF.secureTextEntry = YES;
            NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:@"请输入密码（6-12位数字字母组合）" attributes:@{NSForegroundColorAttributeName :  [UIColor colorWithHexString:@"#adadad"]}];
            cell.textTF .attributedPlaceholder = placeholderString;
            cell.iconImage.image = [UIImage imageNamed:@"login_icon_10"];
           // cell.textTF.text = @"aa123456";
        }
            break;
            
        default:
            break;
    }

}
-(void)changedTextField:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
        {
               [RestrictionInput restrictionInputTextField:textField maxNumber:11 showView:self.view showErrorMessage:@"0~12字符~"];
        }
            break;
            case 1:
                  {
                      [RestrictionInput restrictionInputTextField:textField maxNumber:12 showView:self.view showErrorMessage:@"0~12字符~"];
                  }
                      break;

        default:
            break;
    }
 
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[self dismissViewControllerAnimated:YES completion:nil];

}


-(void)reBtnClik{
    
    
    [self authVerification];
 
    
    
}

#pragma mark - 验证TouchID/FaceID
- (void)authVerification {
    
    YZAuthID *authID = [[YZAuthID alloc] init];
    
    [authID yz_showAuthIDWithDescribe:nil block:^(YZAuthIDState state, NSError *error) {
        
        if (state == YZAuthIDStateNotSupport) { // 不支持TouchID/FaceID
            NSLog(@"对不起，当前设备不支持指纹/面容ID");
            [JMNotifyView showNotify:@"对不起，当前设备不支持指纹/面容ID" isSuccessful:NO];
        } else if(state == YZAuthIDStateFail) { // 认证失败
            NSLog(@"指纹/面容ID不正确，认证失败");
             [JMNotifyView showNotify:@"指纹/面容ID不正确，认证失败" isSuccessful:NO];
        } else if(state == YZAuthIDStateTouchIDLockout) {   // 多次错误，已被锁定
            NSLog(@"多次错误，指纹/面容ID已被锁定，请到手机解锁界面输入密码");
             [JMNotifyView showNotify:@"指纹/面容ID不正确，认证失败" isSuccessful:NO];
        } else if (state == YZAuthIDStateSuccess) { // TouchID/FaceID验证成功
            NSLog(@"认证成功！");
            [JMNotifyView showNotify:@"认证成功！请完成注册" isSuccessful:YES];
            ZDBRegisterViewController * reVC = [ZDBRegisterViewController new];
             reVC.title = @"注册";
             [self.navigationController pushViewController:reVC animated:YES];
            
        }
        
    }];
}


-(void)back{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
-(BOOL)isMobileNumChack:(NSString *)input{
    
    input = [input stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (input.length != 11) {
        return NO;
    } else {
        
        //^((13[0-9])|(14[1]|[4-9])|(15([0-3]|[5-9]))|(16[2]|[5-7])|(17[0-3]|[5-8])|(18[0-9])|(19[1|8|9]))\\d{8}$
        
        NSString * CT = @"^1[3|4|5|6|7|8|9][0-9]{9}$";
        NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
        BOOL res4 = [regextestct evaluateWithObject:input];
        if (res4 ) {
            return YES;
        }else {
            return NO;
        }
    }
    
}
#pragma mark ------setter   ---getter
-(TPKeyboardAvoidingTableView*)ks_TableView2
{
    if (_ks_TableView2==nil) {
        _ks_TableView2=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _ks_TableView2.separatorColor=[UIColor clearColor];
        _ks_TableView2.delegate=self;
        _ks_TableView2.backgroundColor = [UIColor clearColor];
        _ks_TableView2.dataSource=self;
        _ks_TableView2.sectionFooterHeight=0.01;
        _ks_TableView2.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _ks_TableView2.estimatedRowHeight =0;
            _ks_TableView2.estimatedSectionHeaderHeight =0;
            _ks_TableView2.estimatedSectionFooterHeight =0;
            _ks_TableView2.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    return _ks_TableView2;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
